<template>
  <!-- 核实dialog-->
  <el-dialog
    title="事件核实"
    :visible="visible"
    class="dialog-class1 dialogStyle"
    :destroy-on-close="true"
    @opened="openFun"
    @close="resetFun"
    :z-index="2000"
    width="560px"
  >
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="84px"
      class="form"
      style="margin-right: 50px"
      v-loading="loading"
    >
      <el-form-item label="下一环节" prop="flowLink">
        <el-select
          v-model="ruleForm.flowLink"
          @change="getUserTree"
          placeholder="请选择"
        >
          <el-option
            v-for="(item, index) in nextLinkList"
            :key="index"
            :value="item.linkId"
            :label="item.linkName"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="处理人"
        class="select-user"
        prop="userList"
        v-if="nextLinkList.length > 0 && ruleForm.flowLink != 6"
      >
        <tree-select
          v-model="ruleForm.userList"
          :allUserTreeData="allUserTreeData"
          :userTreeData="userTreeData"
          node-key="id"
          ref="treeSelect"
          default-expand-all
          show-checkbox
          :config="{ label: 'userName', value: 'userId' }"
          :isShowAllBtn="isShowAllBtn"
          :isShowAllInfo.sync="isShowAllInfo"
          :nextLinkInfo="
            this.nextLinkList.find(
              (item) => item.curLink == this.ruleForm.flowLink
            )
          "
        />
      </el-form-item>
      <div class="position-info">
        <editUsefulWord
          :isShowUsefulWord.sync="isShowUsefulWord"
        ></editUsefulWord>
      </div>
      <el-form-item label="核实说明" prop="desc">
        <el-input
          type="textarea"
          resize="none"
          v-model="ruleForm.desc"
          @input="ruleForm.desc = ruleForm.desc.replace(/\s+/g, '')"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item v-show="isShowUsefulWord">
        <useful-word
          style="margin-top: -21px"
          :desc.sync="ruleForm.desc"
          :isShowUsefulWord.sync="isShowUsefulWord"
        ></useful-word>
      </el-form-item>

      <el-form-item style="margin-bottom: 0">
        <FormItemIconTipLabel slot="label" />
        <EventFileUpload
          v-model="ruleForm.orderFileDTOList"
          :loading.sync="uploading"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button
        @click="submitFun('ruleForm')"
        type="primary"
        :loading="btnLoading || uploading"
        style="margin-right: 10px"
        >确 定</el-button
      >
      <el-button @click="resetFun">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { $store, $getUrlParam } from "@/utils/public";
import {
  queryNextLink,
  getUserTree,
} from "@/api/modules/eventManagement/eventDispatch.js";
import {
  submitOrderApproveInfo,
  rollBack,
} from "@/api/modules/eventManagement/eventCheck";
import { getFlow } from "@/api/modules/eventManagement/getFlowId";
import ElImageViewer from "@/components/ElImgViewer";
import TreeSelect from "@/components/TreeSelect";
import UsefulWord from "@/views/pages/eventManagement/eventDialog/usefulWord";
import editUsefulWord from "@/views/pages/eventManagement/eventDialog/editUsefulWord";
import EventFileUpload from "../components/EventFileUpload";
import FormItemIconTipLabel from "../components/FormItemIconTipLabel";
export default {
  name: "checkDialog",
  components: {
    ElImageViewer,
    TreeSelect,
    UsefulWord,
    editUsefulWord,
    EventFileUpload,
    FormItemIconTipLabel,
  },
  data() {
    var validateF = (rule, value, callback) => {
      if (this.ruleForm.userList?.length > 0) {
        callback();
      } else {
        callback(new Error("请选择流转人员"));
      }
    };
    return {
      allUserTreeData: [],
      isPlay: false,
      showViewer: false,
      imgList: [],
      selectImageIndex: "",
      audioLength_original: 0,
      audioLength: 0,
      audioInterval: null,
      backLinkList: [],
      userTreeData: [],
      ruleForm: {
        ifFinish: "2",
        operationValue: "",
        userList: [],
        desc: "",
      },
      rules: {
        ifFinish: [
          { required: true, message: "请选择", trigger: ["blur", "change"] },
        ],
        operationValue: [
          { required: true, message: "请选择", trigger: ["blur", "change"] },
        ],
        flowLink: [
          { required: true, message: "请选择", trigger: ["blur", "change"] },
        ],
        userList: [
          { validator: validateF, required: true, trigger: ["blur", "change"] },
        ],
        desc: [
          {
            required: true,
            message: "请输入核实说明",
            trigger: ["blur", "change"],
          },
        ],
      },
      operationList: [
        { code: "1", name: "回退" },
        { code: "0", name: "重新分派" },
      ],
      showBigImageVisible: false,
      bigImageUrl: "",
      nextLinkList: [],
      flowId: "",
      flowTemplate: "",
      previewDialog: false,
      loading: false,
      isTenantAdmin: this.$store.getters.userInfo.isTenantAdmin, // 1 租户管理员
      isShowAllBtn: true /** 是否显示全部处理人按钮 */,
      isShowAllInfo: false, // 是否显示全部处理人
      isShowUsefulWord: false, // 是否显示常用语列表
      btnLoading: false,
      uploading: false,
    };
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    orderData: {
      type: Object,
      default: {},
    },
  },
  methods: {
    getUserTree(linkParam) {
      if (linkParam == "6") {
        return;
      }
      const selectLinkData = this.nextLinkList.filter(
        (item) => item.linkId === linkParam
      );
      this.isShowAllBtn = !(
        selectLinkData[0].dataFilterPermiss === "0" &&
        selectLinkData[0].customAdmin === "1"
      );
      this.isShowAllInfo =
        selectLinkData[0].dataFilterPermiss === "0" && !this.isShowAllBtn;
      const params = {
        curLink: linkParam,
        tenantId: this.$store.getters.userInfo.tenantId
          ? this.$store.getters.userInfo.tenantId
          : this.orderData.tenantId,
        flowId: this.orderData.flowId,
        deviceCode: this.orderData.deviceCode,
        provinceId: this.orderData.provinceId,
        cityId: this.orderData.cityId,
        countyId: this.orderData.countyId,
        warningSource: this.orderData.warningSource,
        gridId: this.orderData.gridId,
        warningTypeId: this.orderData.warningTypeId,
      };
      this.loading = true;
      getUserTree(params).then((res) => {
        this.loading = false;
        if (res.code === 200) {
          this.userTreeData = this.transferTreeData([res.data.sysPowerInfo]);
          this.allUserTreeData = this.transferTreeData([res.data.sysAllInfo]);
          this.userTreeData[0].root = 1;
          this.allUserTreeData[0].root = 1;
          this.$nextTick(() => {
            this.$refs.treeSelect.checkTreeChange();
          });
        }
      });
    },
    // 字段转换
    transferTreeData(list) {
      return list.map((node) => {
        const { nodeId, ...rest } = node;
        let nodeName = node.userName || node.nodeName;
        const obj = {
          id: nodeId,
          label: nodeName,

          ...rest,
        };
        if (node.children) {
          return {
            ...obj,
            children: this.transferTreeData(node.children),
          };
        }
        return obj;
      });
    },
    async selectNextLinkList() {
      const _this = this;
      let params = {
        curLink: _this.orderData.linkId,
        flowId: _this.flowId,
        warningSource: _this.orderData.warningSource,
        templateId: _this.orderData.flowTemplate,
      };
      if (params.curLink == 6) {
        return;
      }
      const res = await queryNextLink(params);
      if (res.code === 200) {
        _this.nextLinkList = res.data;
        if (_this.nextLinkList && _this.nextLinkList.length === 1) {
          _this.ruleForm.flowLink = res.data[0].linkId;
          _this.ruleForm = JSON.parse(JSON.stringify(_this.ruleForm));
          this.getUserTree(this.ruleForm.flowLink);
        }
      }
    },
    async getFlowIds(tenantId, warningSource, alarmCode) {
      const _this = this;
      const resp = await getFlow({
        tenantId: tenantId,
        warningSource: warningSource,
        alarmCode: alarmCode,
      });
      if (resp.code == 200) {
        let flowFlow = tenantId + "_" + warningSource;
        // flowId = resp.data.flowId;
        _this.flowId = resp.data[flowFlow];
        _this.flowTemplate = _this.orderData.flowTemplate
          ? _this.orderData.flowTemplate
          : _this.flowId;
        await this.selectNextLinkList();
      } else {
        console.log("");
      }
    },
    async openFun() {
      this.btnLoading = false;
      this.loading = false;
      const _this = this;
      _this.flowTemplate = _this.orderData.flowTemplate;
      if (!_this.orderData.flowId && !_this.flowId) {
        await _this.getFlowIds(
          _this.orderData.tenantId,
          _this.orderData.warningSource,
          _this.orderData.warningTypeId
        );
      } else {
        _this.flowId = _this.flowId ? _this.flowId : _this.orderData.flowId;
        await this.selectNextLinkList();
      }
    },
    //提交
    submitFun(formName) {
      let _this = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (_this.ruleForm.desc.length > 200) {
            $message.error("核实说明不能超过200字！");
            return;
          }
          //默认下一环节为已完结
          let cruLink = "6";
          //核实
          if (_this.ruleForm.ifFinish == "2") {
            let flowInfo = {};
            //下一环节有数据则取下一环节id
            if (_this.nextLinkList.length >= 1) {
              flowInfo = _this.nextLinkList.find(
                (ele) => ele.curLink === _this.ruleForm.flowLink
              );
              cruLink = flowInfo.curLink;
              flowInfo.nextEnableAcceptanceMode = flowInfo.enableAcceptanceMode;
              flowInfo.enableAcceptanceMode =
                this.orderData.enableAcceptanceMode;
            }

            let params = {
              ...flowInfo,
              linkId: cruLink,
              flowId: _this.flowId,
              flowTemplate: _this.flowTemplate,
              orderId: _this.orderData.warningOrderId,
              warningOrderId: _this.orderData.warningOrderId,
              operator: $store.get("$loginInfo").userId,
              orderApproveVOList: [
                {
                  approveStatus: _this.ruleForm.ifFinish, //0:审批失败 1:待审批 2:审批通过
                  approveResult: _this.ruleForm.desc,
                },
              ],
              voice: "",
              orderFileDTOList: this.ruleForm.orderFileDTOList, // 附件
            };
            params.isNextLink = "1";
            params.isSign = "0";
            if (this.ruleForm.flowLink != "6") {
              // 下一环节不是完结
              params.realLinkType = this.nextLinkList.filter(
                (item) => item.linkId == this.ruleForm.flowLink
              )[0].realLinkType;
              params.flowLinkType = "0";
              params.processDTOList = this.ruleForm.userList.map((ele) => ({
                processId: ele.userId,
                processName: ele.userName,
              }));
            } else {
              // 下一环节为完结
              params.realLinkType = "6";
              params.flowLinkType = "0";
              params.processDTOList = [];
            }
            if (this.orderData.updateAddress) {
              params.address = this.orderData.address;
              params.longitude = this.orderData.longitude;
              params.latitude = this.orderData.latitude;
              params.gridId = this.orderData.gridId;
              params.gridName = this.orderData.gridName;
              params.horiAzimuthAngle = this.orderData.horiAzimuthAngle;
              params.checkGridFlag = "1"; // 是否修改网格员  1 是  0 否
            } else {
              params.checkGridFlag = "0";
            }
            this.btnLoading = true;
            params.cityId = this.orderData.cityId;
            params.countyId = this.orderData.countyId;
            params.provinceId = this.orderData.provinceId;
            params.devicePitch = this.orderData.devicePitch; // 俯仰角
            params.alarmReason = this.orderData.alarmReason; // 告警原因
            params.deviceHorizontal = this.orderData.deviceHorizontal; // 水平角
            submitOrderApproveInfo(params).then((resp) => {
              this.btnLoading = false;
              let msgId = {
                id: this.orderData.warningOrderId,
                status: this.orderData.orderStatus,
              };
              this.$store.dispatch("closeSocketMsg", msgId);
              if (resp && resp.code == 200) {
                let userId = this.$store.getters.userInfo.userId;
                if (
                  ((Array.isArray(this.ruleForm.userList) &&
                    this.ruleForm.userList.find(
                      (item) => item.userId == userId
                    )) ||
                    this.isTenantAdmin == "1") &&
                  this.ruleForm.flowLink != "6"
                ) {
                  // 有下一环节处理权限就自动打开下一环节
                  this.$store.dispatch("tagsView/delView", this.$route);
                  this.refreshSelectedTag(this.$route, params.realLinkType);
                } else {
                  _this.onSuccess();
                }
                _this.resetForm();
                $message.success("核实成功");
              } else {
                $message.error(resp.mess);
              }
            });
          } else if (_this.ruleForm.ifFinish == "0") {
            //回退
            if (_this.ruleForm.operationValue == "") {
              $message.warning("操作不能为空！");
              return;
            }
            //如果当前事件没有调度环节，则不能回退到调度
            if (_this.orderData.ifSend == "0") {
              if (this.ruleForm.operationValue == "0") {
                $message.warning("该事件无调度环节，无法重新分派");
                return;
              }
            }
            let flowDataInfo = {};
            for (let i = 0; i < _this.backLinkList.length; i++) {
              let row = _this.backLinkList[i];
              if (row.linkId == _this.ruleForm.operationValue) {
                flowDataInfo = row;
                break;
              }
            }
            let params = {
              ...flowDataInfo,
              flowId: _this.flowId,
              flowTemplate: _this.flowTemplate,
              orderId: _this.orderData.orderId,
              warningOrderId: _this.orderData.warningOrderId,
              currentOrderStatus: "5", //4-处置；5-核实
              backType: _this.ruleForm.operationValue, //0-回退到调度 1-回退到处置
              remark: _this.ruleForm.desc,
              orderApproveVOList: [
                {
                  approveStatus: _this.ruleForm.ifFinish, //0:审批失败 1:待审批 2:审批通过
                  approveResult: _this.ruleForm.desc,
                },
              ],
              orderFileDTOList: _this.ruleForm.orderFileDTOList, // 附件
            };
            if (this.backLinkList.length === 1) {
              params.backType = this.backLinkList[0].linkId;
            }
            rollBack(params).then((resp) => {
              if (resp && resp.code == 200) {
                $message.success("回退成功");
                // this.$router.push({ path: "/event" });
                const url =
                  $getUrlParam("pageType") === "false"
                    ? "/eventManagement"
                    : "/eventManagement/myEvent";
                this.$close(url);
              } else {
                $message.error(resp.msg);
              }
            });
          }
          _this.$emit("checkCancelFun", false);
        }
      });
    },
    resetFun() {
      this.imgList = [];
      this.ruleForm = {
        ifFinish: "2",
        operationValue: "",
        desc: "",
      };
      this.userTreeData = [];
      this.isShowAllBtn = false; /** 是否显示全部处理人按钮 */
      this.isShowAllInfo = false; // 是否显示全部处理人
      this.isShowUsefulWord = false; // 是否显示常用语列表
      this.$emit("update:visible", false);
    },
    refreshSelectedTag(view, realLinkType) {
      location.reload();
    },
    replaceParamVal(oUrl, paramName, replaceWith) {
      var re = eval("/(" + paramName + "=)([^&]*)/gi");
      var nUrl = oUrl.replace(re, paramName + "=" + replaceWith);
      return nUrl;
    },
    onSuccess() {
      const url =
        $getUrlParam("pageType") === "false"
          ? "/eventManagement"
          : "/eventManagement/myEvent";
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push(url);
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-dialog > .el-dialog__body {
  padding: 12px 60px 0;
}

/deep/ .el-upload--picture-card {
  border-radius: 5px;
}
/deep/ .imageClass {
  width: 80px;
  height: 50px;
}
/deep/ .el-form-item__error {
  position: relative;
}
/deep/.select-user .el-form-item__error {
  position: absolute;
  top: 35px;
  left: 5px;
}
/deep/ .submitClass {
  background: #ff6a6c !important;
  color: #ffffff !important;
}
/deep/ .style1 .el-form-item label {
  height: 32px !important;
  line-height: 32px !important;
}
/deep/ .el-image {
  display: contents !important;
}
// /deep/ .video-player {
//   width: 100%;
//   height: calc(80vh - 114px);
//   pointer-events: none;
//   border-radius: 15px;
// }
// /deep/.video-player /deep/ video {
//   width: 100%;
//   height: calc(80vh - 114px);
//   border-radius: 15px;
// }
// /deep/.video {
//   height: calc(80vh - 114px);
//   background: #22222c;
//   box-shadow: 0px 10px 12px 2px rgba(213, 210, 233, 0.59);
//   border-radius: 15px;
//   margin-bottom: 10px;
// }
.audioStyle {
  width: 150px;
  height: 32px;
  background: #f2f5f8;
  border-radius: 20px;
  border: 1px solid #cddbe6;
  line-height: 32px;
  color: #98a0a7;
}
#voice_id label {
  height: 32px;
  line-height: 32px;
}

.form {
  /deep/ .el-form-item--small.el-form-item {
    margin-bottom: 20px;
  }
  /deep/ .el-form-item {
    .el-form-item__label {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #606266;
      line-height: 32px;
    }

    .el-form-item__content {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #606266;
    }
  }
}

.dialog-class1 {
  /deep/ .el-dialog__body {
    overflow-x: hidden;
  }
}

.video {
  //width: 150px;
  border-radius: 5px;
  height: 100%;
  margin-right: 5px;
}
.video-file-item {
  height: 55px;
  width: 90px;
  border-radius: 5px;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  margin-right: 10px;
  margin-bottom: 10px;
}
.mask {
  height: 100%;
  width: 100%;
  background: rgba(0, 0, 0, 0.7);
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  opacity: 0;
  transition: all 0.3s;
  align-items: center;
  justify-content: center;
  i {
    color: #fff;
    font-size: 22px;
    cursor: pointer;
  }
}
.video-file-item:hover .mask {
  opacity: 1;
}
/deep/.el-carousel {
  height: 100%;
}
/deep/.el-carousel__item {
  display: flex;
  align-items: center;
  justify-content: center;
}
/deep/.video-preview-dialog .el-carousel__arrow {
  display: none;
}
/deep/ .el-form-item__content {
  display: flex;
  flex-wrap: wrap;
}
/deep/.el-dialog__wrapper .el-dialog__body .el-form-item__label {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #606266;
}
.position-info {
  margin-top: -10px;
  padding-right: 5px;
  margin-bottom: 5px;
}
.dialogStyle {
  /deep/ .el-dialog {
    border-radius: 4px;
  }
  /deep/ .el-dialog__header {
    padding: 12px;
  }
  /deep/ .el-dialog__footer {
    padding: 12px;
  }
  /deep/ .el-form-item--small.el-form-item {
    margin-bottom: 12px;
  }
  /deep/ .el-form-item .el-form-item__label {
    padding-right: 9px;
  }
  /deep/ .el-textarea__inner {
    height: 140px;
  }
}
</style>
